<template>
  <div class="app-container">
    <div>
        <el-input v-model="roleViewModel.RoleName" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="queryRole" />
      <el-button type="primary" @click="queryRole" icon="el-icon-search">查询角色</el-button>
      <el-button type="primary" @click="handleAddRole" icon="el-icon-plus">新增角色</el-button>
    </div>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">{{ scope.row.RoleName }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色类别" >
        <template slot-scope="scope">{{ scope.row.RoleAuthorizationType }}</template>
      </el-table-column>
      <el-table-column align="center" label="标识码">
        <template slot-scope="scope">{{ scope.row.Code }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">{{ scope.row.CreateTime | formatDateSec}}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="roleViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="roleViewModel.pageSize"
        @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
        :total="roleViewModel.total"></el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新增角色'">
      <el-form :model="role" :rules="rules" ref="role" label-width="100px" label-position="right">
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="role.RoleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="标识码" prop="Code">
          <el-input v-model="role.Code" placeholder="标识码" />
        </el-form-item>
        <el-form-item label="角色类别" prop="RoleAuthorizationType">
          <el-input v-model="role.RoleAuthorizationType" placeholder="角色类别" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="role.Text" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="备注" />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree ref="tree" :data="routesData" :props="defaultProps" show-checkbox default-expand-all node-key="id"
            class="permission-tree" />
        </el-form-item>
        <div style="text-align:right">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmRole('role')">确认</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import path from "path";
  import { deepClone } from "@/utils";
  import {
    getRoutes,
    getRoles,
    addRole,
    deleteRole,
    updateRole
  } from "@/api/role";

  const defaultRole = {
    RoleID: "",
    RoleName: "",
    RoleAuthorizationType: "",
    Code: "",
    Text: "",
    routes: [],
    MenuIdList: []
  };

  export default {
    data() {
      return {
        role: Object.assign({}, defaultRole),
        routes: [],
        rolesList: [],
        dialogVisible: false,
        dialogType: "new",
        checkStrictly: true,
        defaultProps: {
          children: "children",
          label: "title"
        },
        roleViewModel: {
          page: 1,
          pageSize: 10,
          total: 60,
          RoleName:''
        },
        ruleForm: {
          RoleName: "",//最好与model字段名称一致，否则验证有些问题
          Code: "",
          RoleAuthorizationType: ""
        },
        rules: {
          RoleName: [
            { required: true, message: "请输入角色名称", trigger: "change" },
            {
              min: 1,
              max: 50,
              message: "长度在 1 到 50 个字符",
              trigger: "change"
            }
          ],
          Code: [{ required: true, message: "请输入标识码", trigger: "change" }],
          RoleAuthorizationType: [
            { required: true, message: "请输入角色类型", trigger: "change" }
          ]
        }
      };
    },
    computed: {
      routesData() {
        return this.routes;
      }
    },
    created() {
      // Mock: get all routes and roles list from server
      this.getRoutes();
      this.getRoles(this.roleViewModel);
    },
    methods: {
      async getRoutes() {
        const res = await getRoutes();
        this.serviceRoutes = res.Data;
        this.routes = res.Data;
      },
      async getRoles(roleViewModel) {
        const res = await getRoles(roleViewModel);
        if (res.Data && res.Data.length > 0) {
          this.roleViewModel.total = res.Data[0].Total;
        }
        this.rolesList = res.Data;
      },
      queryRole(){
        this.getRoles(this.roleViewModel);
      },
      lastPage(val) {
        this.roleViewModel.page = val;
      },
      nextPage(val) {
        this.roleViewModel.page = val;
      },
      handleSizeChange(val) {
        this.roleViewModel.pageSize = val;
        this.getRoles(this.roleViewModel);
      },
      handleCurrentChange(val) {
        this.roleViewModel.page = val;
        this.getRoles(this.roleViewModel);
      },
      handleAddRole() {
        this.role = Object.assign({}, defaultRole);
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([]);
        }
        this.dialogType = "new";
        this.dialogVisible = true;
      },
      handleEdit(scope) {
        this.dialogType = "edit";
        this.dialogVisible = true;
        this.role = deepClone(scope.row);
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.role.MenuIdList);
        });
      },
      handleDelete({ $index, row }) {
        this.$confirm("确认删除角色?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await deleteRole(row.RoleID);
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getRoles(this.roleViewModel);
          })
          .catch(err => {
            console.error(err);
          });
      },
      getCheckedKeys() {
        return this.$refs.tree.getCheckedKeys();
      },
      async confirmRole(formName) {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs[formName].validate(valid => {
          v = valid;
        });
        if (!v) {
          this.$message({
            message: "验证失败",
            type: "error"
          });
          return false;
        }
        const isEdit = this.dialogType === "edit";
        const checkedKeys = this.getCheckedKeys();
        this.role.MenuIdList = checkedKeys;

        if (isEdit) {
          await updateRole(this.role);
          for (let index = 0; index < this.rolesList.length; index++) {
            if (this.rolesList[index].RoleID === this.role.RoleID) {
              this.rolesList.splice(index, 1, Object.assign({}, this.role));
              break;
            }
          }
        } else {
          const res = await addRole(this.role);
          var data = res.Data
          this.role.RoleID = data.RoleID;
          this.rolesList.push(this.role);
        }

        this.dialogVisible = false;
        this.$message({
          message: `操作成功`,
          type: "success"
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 30px;
    }
  }
</style>